import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Button, Input, Select, message, Modal } from 'antd'
import { ExclamationCircleOutlined, UpOutlined, DownOutlined } from '@ant-design/icons'
import style from './SeriesCaseDetail.module.less'
import CaseSelector from '@components/SeriesCase/CaseSelector'
import SeriesModal from '@components/SeriesCase/SeriesModal'
import SecretarySelect from '@components/SecretarySelect'
import ArbitratorSelect from '@components/ArbitratorSelect'
import { addResizeEvent, delResizeEvent } from '@redux/actions'
const { Item } = Form
const { Option } = Select
const { confirm } = Modal
const layout = {
  labelCol: { flex: '72px' }
}
class SeriesCaseDetail extends Component {
  state = {
    height: window.document.documentElement.offsetHeight - 135,
    scrollHandleName: `series-detail-${Date.now()}`,
    searchHeight: 0,
    isAdding: false,
    id: undefined,
    ready: false,
    caseList: [],
    secretaryList: [],
    condition: [
      { k: 'status', o: '=', v: '交费' }
    ],
    caseno: undefined,
    applicant: undefined,
    respondent: undefined,
    seriesVisible: false,
    version: Date.now(),
    showAll: false,
    treeData: [],
    dictionaries: {} // 枚举字典
  }

  formRef = React.createRef()
  searchRef = React.createRef()

  // 获取秘书列表
  initSecreataryList () {
    this.$get('/api/xapc/employee/getCaseProcesser')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          secretaryList: res.data
        })
      })
  }

  // 初始化选择器的高度
  initSelectHeight () {
    const { isAdding } = this.state
    const wH = window.document.documentElement.offsetHeight
    const searchRef = this.searchRef.current
    let sH = searchRef ? searchRef.offsetHeight : 24
    if (sH === 0 && isAdding) {
      sH = this.state.searchHeight
    }
    const h = wH - 135 - sH
    this.setState({
      height: h < 400 ? 400 : h,
      searchHeight: sH > 0 ? sH : this.state.searchHeight
    })
  }

  // 根据传递的id数据判断是新增还是编辑
  initDataFromMeta () {
    const { id } = this.props.meta || {}
    const obj = { ready: true }
    if (id) {
      obj.id = id
      obj.isAdding = false
    } else {
      obj.isAdding = true
    }
    this.setState(obj, () => {
      this.initSelectHeight()
    })
  }

  // 获取搜索条件
  changeCondition (form) {
    const condition = []
    if (form.status === '全部') {
      condition.push({ k: 'status', o: 'in', v: '交费,立案,移交送达,送达完成,移交办案,已组庭' })
    } else {
      condition.push({ k: 'status', o: '=', v: form.status })
    }
    if (form.procedure && form.procedure.length) {
      condition.push({ k: 'procedure', o: 'in', v: form.procedure.join() })
    }
    if (form.processerid) {
      condition.push({ k: 'processerid', o: '=', v: form.processerid })
    }
    if (form.arbitratorid) {
      condition.push({ k: 'arbitratorids', o: 'like', v: `%${form.arbitratorid}%` })
    }
    if (form.accept_structure) {
      condition.push({ k: 'accept_structure', o: '=', v: form.accept_structure })
    }
    this.setState({
      condition,
      caseno: form.caseno,
      applicant: form.applicant,
      respondent: form.respondent
    })
  }

  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({ condition: [{ k: 'status', o: '=', v: '交费' }], caseno: undefined, applicant: undefined, respondent: undefined })
  }

  // 创建系列案
  createSeries (list = []) {
    if (list.length === 0) {
      return message.warning('请勾选要创建系列案的案件')
    }
    this.setState({ caseList: list, seriesVisible: true })
  }

  // 创建系列案请求
  seriesFinishHandle (d) {
    const hide = message.loading('提交中', 120)
    this.$post('/api/xapc/caseserie', {
      ...d,
      caseids: this.state.caseList.map(li => li.id).join()
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      message.success('合成成功', 1, () => {
        this.props.delWindow(this.props.id)
        this.props.addWindow({ id: 'SeriesCaseManage', title: '系列案管理', componentName: 'SeriesCaseManage', forceRefresh: true })
      })
    }).catch(() => hide())
  }

  // 批量移除案件
  multiRemove (list) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要批量移除案件吗？',
      onOk: () => {
        this.multiRemoveRequest(list)
      }
    })
  }

  // 移除某个案件
  removeHandle (d) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `您确定要移除 ${d.caseno_desc || d.acceptno_desc} 吗？`,
      onOk: () => {
        this.multiRemoveRequest([d])
      }
    })
  }

  // 批量移除请求
  multiRemoveRequest (list = []) {
    const hide = message.loading('移除中', 120)
    this.$put(`/api/xapc/caseserie/removeCase/${this.props.meta.id}`, {
      caseids: list.map(li => li.id).join()
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({ version: Date.now() })
    }).catch(() => hide())
  }

  // 添加案件到系列中
  addCasesToSeries (list = []) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要将所选案件添加到系列中吗？',
      onOk: () => {
        this.addCasesRequest(list)
      }
    })
  }

  // 添加案件到系列请求
  addCasesRequest (list = []) {
    const hide = message.loading('提交中', 120)
    this.$put(`/api/xapc/caseserie/addCase/${this.props.meta.id}`, {
      caseids: list.map(li => li.id).join()
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({ version: Date.now(), isAdding: false }, () => this.initSelectHeight())
    }).catch(() => hide())
  }

  // 获取案由树数据
  getTreeData () {
    this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({ treeData: res.data })
      })
  }

  // 获取枚举的字典值
  dictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '结案类型,仲裁程序,案件区域分类,案件来源'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 格式化金钱
  formatMoney (money) {
    if (money) {
      return String(money).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
    return money
  }

  // 将文本转化为数字类型
  transformNumber (v) {
    if (v) {
      return Number(v)
    }
  }

  componentDidMount () {
    this.getTreeData()
    this.dictionary()
    this.initSecreataryList()
    this.initDataFromMeta()
    this.props.addResizeEvent({ name: this.state.scrollHandleName, handle: () => this.initSelectHeight() })
  }

  componentWillUnmount () {
    this.props.delResizeEvent(this.state.scrollHandleName)
  }

  renderOperateBtn (list) {
    const { id, isAdding } = this.state
    if (id) {
      if (isAdding) {
        return (
          <>
            <Button onClick={() => this.setState({ isAdding: false }, () => this.initSelectHeight())}>取消添加</Button>
            <Button type='primary' disabled={list.length === 0} onClick={() => this.addCasesToSeries(list)}>确认添加</Button>
          </>
        )
      }
      return (
        <>
          <Button disabled={list.length === 0} onClick={() => this.multiRemove(list)}>批量移除</Button>
          <Button type='primary' onClick={() => this.setState({ isAdding: true }, () => this.initSelectHeight())}>添加案件</Button>
        </>
      )
    }
    return (
      <>
        <Button type='primary' onClick={() => this.createSeries(list)}>创建系列案</Button>
      </>
    )
  }

  // 当选择器为添加状态时，渲染搜索组件
  renderSearch () {
    const { isAdding, showAll } = this.state
    if (!isAdding) {
      return null
    }
    const initialValues = { status: '交费' }
    return (
      <div className={style['search-container']} ref={this.searchRef}>
        <div className={style['search-form']}>
          <Form name='my_case_manage' {...layout} initialValues={initialValues} ref={this.formRef} onFinish={v => this.changeCondition(v)}>
            <Row gutter={24}>
              <Col span={8}>
                <Item label='案号' name='caseno'>
                  <Input placeholder='请输入案号' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='案件状态' name='status'>
                  <Select placeholder='请选择案件状态'>
                    <Option value='全部'>全部</Option>
                    <Option value='交费'>交费</Option>
                    <Option value='移交送达'>移交送达</Option>
                    <Option value='送达完成'>送达完成</Option>
                    <Option value='移交办案'>移交办案</Option>
                    <Option value='已组庭'>已组庭</Option>
                  </Select>
                </Item>
              </Col>
              <Col span={8}>
                <Item label='申请人' name='applicant'>
                  <Input placeholder='请输入申请人' />
                </Item>
              </Col>
            </Row>
            {this.renderOtherSearch()}
            <Row gutter={24}>
              <Col span={16} />
              <Col span={8}>
                <Item>
                  <div className={style['search-btns']}>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                    <Button type='link' onClick={() => this.setState({ showAll: !this.state.showAll }, () => this.initSelectHeight())}>
                      <span>{showAll ? '收起' : '展开'}</span>
                      {showAll ? <UpOutlined /> : <DownOutlined />}
                    </Button>
                  </div>
                </Item>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
    )
  }

  // 渲染其他搜索项
  renderOtherSearch () {
    if (!this.state.showAll) {
      return null
    }
    const { dictionaries } = this.state
    const procedureList = dictionaries['仲裁程序'] || []
    return (
      <>
        <Row gutter={24}>
          <Col span={8}>
            <Item label='被申请人' name='respondent'>
              <Input placeholder='请输入被申请人' />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='办案秘书' name='processerid'>
              <SecretarySelect />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='仲裁员' name='arbitratorid'>
              <ArbitratorSelect />
            </Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <Item label='仲裁程序' name='procedure'>
              <Select style={{ width: '100%' }} placeholder='请选择仲裁程序' mode='multiple'>
                {procedureList.map(li => (
                  <Option key={li.title} value={li.title}>{li.title}</Option>
                ))}
              </Select>
            </Item>
          </Col>
        </Row>
      </>
    )
  }

  render () {
    const { id, isAdding, height, ready, condition, seriesVisible, version, caseList, caseno, applicant, respondent } = this.state
    const { isFromOther, editable } = this.props.meta || { isFromOther: false }
    return (
      <div className={style.container}>
        <SeriesModal visible={seriesVisible} caseList={caseList} hide={() => this.setState({ seriesVisible: false, caseList: [] })} onFinish={d => this.seriesFinishHandle(d)} />
        {this.renderSearch()}
        <div className={style.content}>
          {ready ? (
            <CaseSelector
              version={version}
              id={id}
              pageid={this.props.id}
              isAdding={isAdding}
              height={height}
              condition={condition}
              renderOperateBtn={d => this.renderOperateBtn(d)}
              removeHandle={d => this.removeHandle(d)}
              isFromOther={isFromOther}
              caseno={caseno}
              applicant={applicant}
              respondent={respondent}
              editable={editable}
            />
          ) : null}
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addResizeEvent: i => dispatch(addResizeEvent(i)),
    delResizeEvent: i => dispatch(delResizeEvent(i))
  }
})

export default connect(mapState, mapDispatch)(SeriesCaseDetail)
